package admin

import (
	"anban/models"
	"anban/service"
	"anban/utils"
	"anban/utils/wechat"
	"fmt"
	"github.com/astaxie/beego"
	"html/template"
	"net/url"
	"strconv"
)

type WithdrawRecordController struct {
	BaseController
}

func (c *WithdrawRecordController) ShowList() {
	curPage, _ := strconv.Atoi(c.GetString("p"))
	if curPage <= 0 {
		curPage = 1
	}
	perCount, _ := beego.AppConfig.Int("percount")
	symPageCount, _ := beego.AppConfig.Int("symmetricpagecount")
	p := map[string]interface{}{}
	realName := c.GetString("real_name")
	c.Data["realName"] = realName
	if len(realName) > 0 {
		p["realName"] = realName
	}
	phone := c.GetString("phone")
	c.Data["phone"] = phone
	if len(phone) > 0 {
		p["phone"] = phone
	}
	status := c.GetString("status")
	if len(status) > 0 {
		p["status"] = status
		c.Data["status"], _ = strconv.Atoi(status)
	} else {
		c.Data["status"] = -1
	}
	p["relation"] = true
	p["convert"] = true
	p["curPage"] = curPage
	p["perCount"] = perCount
	totalCount, recordList := service.GetWithdrawRecordList(p)
	paginator := utils.NewPaginator(int(totalCount), perCount, symPageCount, curPage)
	c.Data["paginator"] = paginator.GetPageHtml()
	c.Data["recordList"] = recordList
	c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
	c.Data["statusList"] = models.WithdrawRecordStatus
	c.TplName = "admin/withdraw_record/list.html"
}

func (c *WithdrawRecordController) Payment() {
	var res *utils.ResJsonStruct
	id := c.GetString("id")

	p := map[string]interface{}{}
	p["relation"] = true
	p["id"] = id
	withdrawRecord := service.GetWithdrawRecordInfo(p)

	if withdrawRecord.Status == 1 {
		res = utils.ResJson(0, "提现记录状态异常", "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	var editInput url.Values
	var addInput url.Values

	enterprisePayment := wechat.NewEnterprisePayment(int(withdrawRecord.Amount*100), withdrawRecord.User.OpenId, withdrawRecord.Sn, "提现收入")
	enterprisePaymentRes, err := enterprisePayment.Pay()

	if err != nil {
		editInput = url.Values{
			"id": {fmt.Sprintf("%d",withdrawRecord.Id)},
			"fail_msg": {err.Error()},
		}
		service.EditWithdrawRecord(editInput)
		res = utils.ResJson(0, err.Error(), "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}
	if enterprisePaymentRes.ReturnCode == "FAIL" || enterprisePaymentRes.ResultCode == "FAIL" {
		editInput = url.Values{
			"id": {fmt.Sprintf("%d",withdrawRecord.Id)},
			"fail_msg": {enterprisePaymentRes.ReturnMsg},
		}
		service.EditWithdrawRecord(editInput)
		res = utils.ResJson(0, enterprisePaymentRes.ReturnMsg, "")
		c.Data["json"] = res
		c.ServeJSON()
		return
	}

	editInput = url.Values{
		"id": {fmt.Sprintf("%d",withdrawRecord.Id)},
		"status": {"1"},
		"fail_msg": {""},
	}
	service.EditWithdrawRecord(editInput)

	addInput = url.Values{
		"user_id": {fmt.Sprintf("%d", withdrawRecord.User.Id)},
		"type": {"2"},
		"amount": {fmt.Sprintf("%f", withdrawRecord.Amount)},
	}
	service.AddFinance(addInput)

	res = utils.ResJson(1, "提现成功", "")
	c.Data["json"] = res
	c.ServeJSON()
}